package com.freedom.monitor.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.freedom.monitor.myeye.config.service.MemberConfigService;
import com.freedom.monitor.myeye.config.service.MemberResult;
import com.freedom.monitor.utils.ConstantUtils;
import com.freedom.monitor.utils.CookieUtils;
import com.freedom.monitor.utils.ExclusionStrategyUtils;
import com.freedom.monitor.utils.StringUtils;
import com.freedom.rpc.thrift.common.utils.Logger;
import com.freedom.rpc.thrift.common.utils.SocketUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Controller
@RequestMapping(value = "/member")
public class MemberController {
	//
	private static final Logger logger = Logger.getLogger(MemberController.class);

	// 首页进来
	@RequestMapping(value = "/index", method = { RequestMethod.GET })
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("index for group...");
		return new ModelAndView("member/index", model);// 返回member/index.jsp
	}

	// 查询所有用户
	@RequestMapping(value = "/query", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String query(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("GroupMemberController.query invoked...");
		try {
			// 1)先获取翻页参数
			String page = request.getParameter("page");
			String rows = request.getParameter("rows");
			if (false == StringUtils.valid(page, rows)) {
				page = "1";
				rows = "10";
			}
			int intPage = Integer.parseInt(page.trim());
			int intRows = Integer.parseInt(rows.trim());
			logger.debug("received --->" + "page->" + page + " rows:" + rows);
			// 2)保证可以拿到当前操作者，也就是cookie没有失效
			String operatorId = (String) CookieUtils.getCookie(request).get(ConstantUtils.COOKIE_USER_ID);
			if (false == StringUtils.valid(operatorId)) {
				throw new Exception("invalid operatorId,not exist in cookie,please re login...");
			}
			// 3)尝试获取远程服务结果
			MemberResult result = new MemberResult();
			logger.debug("try to get ConfigService.Client configServiceClient");
			MemberConfigService.Client memberServiceClient = (MemberConfigService.Client) SocketUtils
					.getSyncAopObject(MemberConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = memberServiceClient.queryMember(intPage, intRows, operatorId);
			// 4)分析结果
			if (null != result && true == result.isSucceed() && null != result.getMemberList()
					&& result.getMemberListSize() >= 0) {
				// 正确且有数据
				logger.debug("memberList---" + result.getMemberList());
				Gson gson = new GsonBuilder().setExclusionStrategies(ExclusionStrategyUtils.getInstance()).create();
				String str = "" + "{\"total\":" + result.getTotal() + ","//
						+ "\"rows\":" + gson.toJson(result.getMemberList())//
						+ "}";
				logger.debug("" + str);
				return str;
			}
			throw new Exception("query member result is not valid");
		} catch (Exception e) {
			logger.error(e.toString());
			return "{\"total\":0,\"rows\":[]}";
		}

	}

	// 新增
	@RequestMapping(value = "/addOrUpdate", method = {
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String addOrUpdate(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.debug("GroupMember.Controller.addOrUpdate() invoked...");
		try {
			// 1)获取参数
			String userid = request.getParameter("userid");
			logger.debug("userid---" + userid);
			String username = request.getParameter("username");
			String name = request.getParameter("name");
			String pwd = request.getParameter("pwd");
			String role = request.getParameter("role");
			if (false == StringUtils.valid(username, name, pwd, role)) {
				throw new Exception("invalid parameter...");
			}
			String createBy = (String) CookieUtils.getCookie(request).get(ConstantUtils.COOKIE_USER_ID);
			if (false == StringUtils.valid(createBy)) {
				throw new Exception("invalid userId,please re login...");
			}
			// 2)调用远程的程序
			logger.debug("try to get UserService.Client userServiceClient");
			MemberConfigService.Client memberServiceClient = (MemberConfigService.Client) SocketUtils
					.getSyncAopObject(MemberConfigService.Client.class);
			logger.debug("succeed to get UserService.Client userServiceClient");
			boolean result = false;
			if (null != userid && userid.trim().length() > 0) {
				logger.debug("action->edit");
				result = memberServiceClient.editMember(username, name, pwd, Integer.parseInt(role), userid);
			} else {
				logger.debug("action->add");
				result = memberServiceClient.addMember(username, name, pwd, Integer.parseInt(role), createBy);
			}
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}

		} catch (Exception e) {
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}

	// 删除
	@RequestMapping(value = "/del", method = { RequestMethod.POST }, produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delete(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		logger.info("GroupMemberController.delete invoked...");
		boolean result = false;
		try {
			// 1)先获取id
			String userId = request.getParameter("userid");
			if (false == StringUtils.valid(userId)) {
				throw new Exception("invalid userId--->" + userId);
			}
			logger.debug("received to be delete user id --->" + userId);
			// 2)尝试获取远程服务结果
			logger.debug("try to get ConfigService.Client configServiceClient");
			MemberConfigService.Client memberServiceClient = (MemberConfigService.Client) SocketUtils
					.getSyncAopObject(MemberConfigService.Client.class);
			logger.debug("succeed to get ConfigService.Client configServiceClient");
			result = memberServiceClient.deleteMember(userId);
			// 拿到了结果
			if (true == result) {
				// 正确且有数据
				return "{\"success\":true}";

			} else {
				return "{\"success\":false}";
			}
		} catch (Exception e) {
			return "{\"success\":false,\"errorMsg\":\"" + e.toString() + "\"}";
		}
	}

}
